package com.liukaixin.product.ru.business.user.myteams;

import android.os.Handler;
import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.liukaixin.product.ru.AppController;
import com.liukaixin.product.ru.data.CallBackListener;
import com.liukaixin.product.ru.data.model.Team;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.data.model.UserTeam;
import com.liukaixin.product.ru.data.repositories.TeamsRepository;
import com.liukaixin.product.ru.util.ACache;
import com.liukaixin.product.ru.util.CheckUtil;
import com.orhanobut.logger.Logger;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by Jacob on 2016/9/15.
 */
public class MyTeamsPresenter implements MyTeamsContract.Presenter {

    @NonNull
    private final TeamsRepository myTeamRepository;

    @NonNull
    private final MyTeamsContract.View myTeamsView;

    private Handler handler = new Handler();

    public MyTeamsPresenter(@NonNull TeamsRepository myTeamRepository,
                            @NonNull MyTeamsContract.View myTeamsView) {
        this.myTeamRepository = checkNotNull(myTeamRepository);
        this.myTeamsView = checkNotNull(myTeamsView);

        this.myTeamsView.setPresenter(this);
    }


    @Override
    public void refresh() {
        myTeamsView.initPage();
        // 获取第一页的十条数据
        getTeamByUserId(1, 10);
    }

    @Override
    public void loadMore(Integer page) {
        getTeamByUserId(page, 10);
    }

    private void getTeamByUserId(final Integer page,
                                 final Integer rows) {
        if (CheckUtil.haveNetWork(myTeamsView.getContext())) {
            myTeamRepository.getTeamsByUserId(page, rows,
                    new CallBackListener<List<UserTeam>>() {
                        @Override
                        public void onCompleted() {
                            //do nothing
                        }

                        @Override
                        public void onError(String msg) {
                            myTeamsView.showError(msg);
                        }

                        @Override
                        public void onNext(List<UserTeam> myTeams) {
                            showDataOnView(myTeams, page);
                        }
                    });
        }
    }

    private void showDataOnView(final List<UserTeam> myTeams,
                                final Integer page) {
        handler.postDelayed(() -> {
            if (page == 1 && myTeams.isEmpty()) {
                myTeamsView.showNoData();
                return;
            }
            if (page == 1) {
                myTeamsView.clearAdapter();
            }
            if (myTeams.size() % 10 > 0
                    || (page != 1 && myTeams.isEmpty())) {
                myTeamsView.setNoMoreData();
            }
            myTeamsView.showData(myTeams);
        }, 1000);
    }
}
